<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: orange;
        }

        span {
            position: absolute;
            left: 0;
            top: 120px;
            background-color: red;
        }

        button {
            position: absolute;
            left: 0;
            top: 200px;
        }
    </style>
</head>
<body>
    <div>动画div盒子</div>
    <span>span标签动画</span>
    <button>点击span标签开始动画</button>

    <script>
        // obj： 需要做动画的对象  target： 动画停止的位置
        // var obj = {}; obj.name = 'andy' 之前我们采用这样的方式给对象的属性赋值
        function startAnimation(obj, target) {
            // 清除对象多余的定时器，使动画对象永远只有一个定时器在执行动画
            clearInterval(obj.timer)
            obj.timer = setInterval(() => {
                if (obj.offsetLeft >= target) {
                    clearInterval(obj.timer);
                }

                obj.style.left = obj.offsetLeft + 1 + 'px';
            }, 10);
        }

        var animationDiv = document.querySelector('div');
        startAnimation(animationDiv, 500);
        var span = document.querySelector('span');
        

        var button = document.querySelector('button');
        button.addEventListener('click', function() {
            startAnimation(span, 200);
        })
    </script> 
</body>
</html> 